﻿package fwk.siteManager2 {	


	import flash.events.EventDispatcher;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode
	import flash.display.StageQuality;
	import fwk.siteManager2.BO.PageData;
	import fwk.siteManager2.BO.RessourceData;
	import fwk.loaderManager.events.LoaderEvent;
	import fwk.siteManager2.managers.DataManager;
	
	import fwk.siteManager2.LoadingDisplayer;
	import fwk.loaderManager.LoaderManager;
	import fwk.loaderManager.LoaderItemObject;
	import fwk.loaderManager.LoaderItemGroup;
	import fwk.loaderManager.LoaderItemType;
	import fwk.loaderManager.events.*;
	import fwk.siteManager2.events.ContainerLoaderEvent;
	
	import fwk.com.asual.swfaddress.*;
	import fwk.com.hexagonstar.util.debug.Debug;
	
	import flash.display.MovieClip;
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.display.LoaderInfo;
	import flash.utils.getDefinitionByName;
	import flash.system.Capabilities;
	
	import fwk.siteManager2.managers.RessourcesManager;
	
	
	/**
	 * Cette classe représente le loader du site. Vous pourvez pas instancier cette classe directement, votre loader principal (qui contient tous le site) doit hérité de cette classe.
	 * Vous pouvr ainsi affecté un LoaderDisplayer personnalisé par exemple avant d'appelé le constructeur de base avec super() : 
	 * @usage <code>
	 *  <br />
	 *  <br />// on set l'url du xml de config pour tester, il faut passer cette variable en flashvars sinon (config)
	 *  <br />urlXmlConfig = "../../configFlash.xml";
	 *  <br />
	 *	<br />// definitions personnalisées des loadersDisplayer du site
	 *	<br />loaderPanelSite = new LoaderDisplayerPerso1(stage);
	 *	<br />loaderPanelPage = new LoaderDisplayerPerso2(stage);
	 *	<br />
	 *	<br />super();
	 *  <br /></code>
	*/
	public class ContainerLoader extends MovieClip
	{
		
		///////////////////////////
		// private properties
		private static var  _instance:ContainerLoader;
		private static var _increment:int = 0;
		
		private var _loaderPanel:LoadingDisplayer;
		private var _loaderPanelSite:LoadingDisplayer;
		private var _loaderPanelPage:LoadingDisplayer;
		private var _loaderManager:LoaderManager;
		

		private var _ressourcesManager:RessourcesManager;
		private var _dataManager:DataManager;
		
		
		private var _urlXmlConfig:String;
		private var _xmlConfig:XML;
		private var _xmlTemplates:XML;
		private var _xmlContentPage:XML;
		private var _loaderItemXmlContent:LoaderItemObject;
		
		private var _repLoc:String;		// repertoire de localisation
		private var _repShared:String;		// repertoire shared
			
		private var _idCurrentPage:String;
		private var _deepLinkToLoad:String;
		private var _deepLinkFirst:String;
		private var _onLoadingPage:Boolean;
		
		private var _flashVarNavigationName:String ;
		private var _flashVarSharedPathName:String ;
		private var _flashVarLocaPathName:String ;
		
		private var _debugMode:Boolean;
		
		//For SWF Address
		private var _isSwfAdd:Boolean;
		private var _splitDeepLink:String;
		private var _listAd:XMLList;
		
		
	

		
		//----------------------------------------------------------------------
		// récup ressources
		//----------------------------------------------------------------------
		/**
		 * Renvoi la ressource global (LoaderItemObject) correspondant à l'id en paramètre. Ce sont les ressources déclarés dans le neoud RessourceGlobal du xml config
		 * @param	id de la ressource
		 * @return LoaderItemObject (package fwk.loaderManager)
		 */
		public function getloaderItemRessourceGlobal(id:String):LoaderItemObject
		{
			return _ressourcesManager.getRessourceGlobal(id);
			
		}
		/**
		 * Renvoi la ressource (LoaderItemObject) correspondant à l'id en paramètre. Ce sont les ressources déclarés dans le neoud structure du xml templates
		 * @param	id de la ressource
		 * @return LoaderItemObject (package fwk.loaderManager)
		 */
		public function getloaderItemStructure(id:String):LoaderItemObject
		{
			return _ressourcesManager.getRessourceClipStructure(id);

		}
		/**
		 * Renvoi le groupe de ressources (LoaderItemGroup) correspondant à l'id en paramètre. Ce sont les groupes déclarés dans le neoud pages du xml templates
		 * @param	id de la ressource
		 * @return LoaderItemGroup (package fwk.loaderManager)
		 */
		public function getLoaderItemPage(id:String):LoaderItemGroup
		{
			
			return _ressourcesManager.getRessourcePage(id) as LoaderItemGroup;

		}
		/**
		 * Renvoi le groupe de ressources (LoaderItemGroup) correspondant à l'id en paramètre. Ce sont les groupes déclarés dans le neoud ressources du xml templates
		 * @param	id de la ressource
		 * @return LoaderItemGroup (package fwk.loaderManager)
		 */
		public function getLoaderItemRessource(id:String):LoaderItemGroup
		{
			
			return _ressourcesManager.getRessourceGroup(id) as LoaderItemGroup;

		}
		/**
		 * Renvoi le groupe de ressources (LoaderItemGroup) correspondant à l'id en paramètre. Ce sont les groupes déclarés dans le neoud templates du xml templates
		 * @param	id de la ressource
		 * @return LoaderItemGroup (package fwk.loaderManager)
		 */
		/*public function getLoaderItemTemplate(id:String):LoaderItemGroup
		{

			return _ressourcesManager.getRessourceTemplate(id) as LoaderItemGroup;
			
			
		}*/

		/*public function get loaderPanel():LoadingDisplayer{
			return _loaderPanel;
		}*/
		public function get xmlContentPage():XML{
			return _xmlContentPage;
		}
		/**
		 * Renvoi le xml templates
		 */
		public function get xmlTemplates():XML{
			return _xmlTemplates;
		}
		/**
		 * Renvoi le xml config
		 */
		public function get xmlConfig():XML{
			return _xmlConfig;
		}
		/**
		 * Renvoi le répertoire country
		 */
		public function get countryPath():String{
			return _repLoc;
		}
		/**
		 * Renvoi le répertoire shared
		 */
		public function get sharedPath():String{
			return _repShared;
		}
		/**
		 * 
		 * @return Instance de ContainerLoader
		 */
		public static function getInstance():ContainerLoader
		{
			
			if ( _instance == null)
			{
				_instance = new ContainerLoader();
			}
			
			return _instance;
		}
		public function get loaderManager():LoaderManager
		{
			return _loaderManager;
		}
		/**
		 * Renvoi le sépérateur du deeplink
		 */
		public function get splitDeepLink():String{
			return _splitDeepLink;
		}
		/**
		 * Renvoi le deeplink à pré-charger à l'arriver dans le site
		 */
		public function get deepLinkToLoad():String{
			return _deepLinkToLoad;
		}
		/**
		 * Indique si le swfAdress est actif 
		 */
		public function get swfAddActif():Boolean{
			return _isSwfAdd;
		}
		
		public function get dataManager():DataManager { return _dataManager; }
		
		public function get ressourcesManager():RessourcesManager { return _ressourcesManager; }
		

		public function get debugMode():Boolean { return _debugMode; }
		
		public function set debugMode(value:Boolean):void 
		{
			_debugMode = value;
		}
		
		public function set splitDeepLink(value:String):void 
		{
			_splitDeepLink = value;
		}
		
		public function set isSwfAdd(value:Boolean):void 
		{
			_isSwfAdd = value;
		}
		
		public function get loaderPanelSite():LoadingDisplayer { return _loaderPanelSite; }
		
		/**
		 * Pour définir le LoadingDisplayer qui est affiché à l'entré sur le site (chargement du site). A definir avant d'appeler le constructeur de base de ContainerLoader
		 */
		public function set loaderPanelSite(value:LoadingDisplayer):void 
		{
			
			if( _loaderPanel == _loaderPanelSite )
				_loaderPanel = value;
				
			_loaderPanelSite = value;
		}
		
		public function get loaderPanelPage():LoadingDisplayer { return _loaderPanelPage; }
		
		/**
		 * Pour définir le LoadingDisplayer qui est affiché au chargement d'une page . A definir avant d'appeler le constructeur de base de ContainerLoader
		 */
		public function set loaderPanelPage(value:LoadingDisplayer):void 
		{
			if( _loaderPanel == _loaderPanelPage )
				_loaderPanel = value;
				
			_loaderPanelPage = value;
		}
		/**
		 * Url du xml de config du site. A definir avant d'appeler le constructeur de base de ContainerLoader
		 */
		public function set urlXmlConfig(value:String):void 
		{
			_urlXmlConfig = value;
		}
		

		

		
		
		
		//-----------------------------------------------------------------------
		// Constructeur
		//-----------------------------------------------------------------------
		function ContainerLoader():void
		{
			
			
		}
		/**
		 * Initialise et commence le chargement du site
		 */
		public function init():void
		{			
			if (stage != null) {
				
				
				
				//alignement
				// stage setup for resizing
				stage.scaleMode						= StageScaleMode.NO_SCALE;
				stage.align							= StageAlign.TOP_LEFT;
				//stage.quality						= StageQuality.HIGH;
				stage.showDefaultContextMenu		= false;
				stage.stageFocusRect				= false;
				

				
				if (_increment == 0) {
					
					
					if( _urlXmlConfig == null) _urlXmlConfig 					= "shared/xml/config.xml";
					_repLoc 						= "";
					_repShared 						= "";
					_flashVarNavigationName 		= "page";
					_flashVarSharedPathName 		= "sharedPath";
					_flashVarLocaPathName 			= "countryPath";
					if( _debugMode != true) _debugMode 						= false;
					
					//For SWF Address
					if( _isSwfAdd != true) _isSwfAdd 						= false;
					if( _splitDeepLink == null) _splitDeepLink 				= "/";

					_onLoadingPage 											= false;

					//recup flashVars
						if(LoaderInfo(loaderInfo).parameters.config != null)
						_urlXmlConfig = LoaderInfo(loaderInfo).parameters.config;
						
					//recup flashVars date
						var datecache:String = "";
						if(LoaderInfo(loaderInfo).parameters.datecache != null)
						datecache = LoaderInfo(loaderInfo).parameters.datecache;
						
					//recup flashVars noCache
					var noCache:String = "false";
					if(LoaderInfo(loaderInfo).parameters.noCache != null)
					noCache = LoaderInfo(loaderInfo).parameters.noCache;
					
					
					// on instancie le gestionnaie de chargement des ressources
					_loaderManager = new LoaderManager();
					if (datecache != "") _loaderManager.idLastCache = datecache; // date du cache à utilisé
					if (noCache == "true") _loaderManager.noCache = true;
					
					
					// init ressources manager
					_ressourcesManager = new RessourcesManager();
					_ressourcesManager.idLastCache = _loaderManager.idLastCache;
					_ressourcesManager.noCache = _loaderManager.noCache;
					
					// data manager
					_dataManager = new DataManager();
					
					
					// on instancie le loader panel du site
					if (_loaderPanelSite == null) _loaderPanelSite = new LoadingDisplayer(stage);
					
					// on instancie le loader panel des pages
					if (_loaderPanelPage == null) _loaderPanelPage = new LoadingDisplayer(stage);
					
					//swfAdress
					SWFAddress.addEventListener(SWFAddressEvent.INIT, onSwfAdressReady);
					
					_instance = this;
					_increment++;
					_deepLinkToLoad = "";
					_deepLinkFirst = "";
					

				}else
				{
					debugIt("Attention !!!! Vous devez utiliser la méthode getInstance() pour récupéré l'instance de la classe ContainerLoader");
				}
			}
			
		}

		
		//----------------------------------------------------------------------
		//-- Methods
		//----------------------------------------------------------------------
		private function onSwfAdressReady(evt:SWFAddressEvent):void 
		{
			//debugIt("onSwfAdressReady");
			SWFAddress.removeEventListener(SWFAddressEvent.INIT, onSwfAdressReady);
			
			

			
			loadConfig();
		
		}
		//----------------------------------------------------------------------
		private function loadConfig():void 
		{
			
			// chargement du xml de config et xml des pages
				// on crée les objects ressource
				var item:LoaderItemObject = new LoaderItemObject("xmlConfig", _urlXmlConfig);
				_ressourcesManager.addToCacheStatic(item);
				
				_loaderManager.add(item);
				_loaderManager.addEventListener(LoaderEvent.COMPLETED, onConfigComplete);
				_loaderManager.start();
		
		}
		//----------------------------------------------------------------------
		/**
		 * Méthode appelé quand le xml config est chargé
		 * @param	evt
		 */
		public function onConfigComplete(evt:LoaderEvent):void
		{
				
			_loaderManager.removeEventListener(LoaderEvent.COMPLETED, onConfigComplete);
			
			
			// on récupère le xml
			_xmlConfig = new XML( (  _ressourcesManager.getRessource("xmlConfig") as LoaderItemObject).content as String);
			
			initDebug();
			
			//default Paths
			_repLoc = _xmlConfig.defaultPaths.@countryPath;
			_repShared = _xmlConfig.defaultPaths.@sharedPath;
			
			//flashVars paths
			if(LoaderInfo(loaderInfo).parameters[_flashVarLocaPathName] != null)
			_repLoc = LoaderInfo(loaderInfo).parameters[_flashVarLocaPathName];
				
			if(LoaderInfo(loaderInfo).parameters[_flashVarSharedPathName] != null)
			_repShared = LoaderInfo(loaderInfo).parameters[_flashVarSharedPathName];
			

			var rep:String;
			rep = _repShared;
			_loaderManager.reset();

			if(_xmlConfig.structure.@url != ""){
			
				if (_xmlConfig.structure.@path != null && _xmlConfig.contentDisplayed.@path == "countryPath") rep = _repLoc;
				if (_xmlConfig.structure.@path != null && _xmlConfig.contentDisplayed.@path == "external") rep = "";
				
				var item:LoaderItemObject = new LoaderItemObject("xmlTemplates", rep+_xmlConfig.structure.@url);			
				_loaderManager.add(item);
				_ressourcesManager.addToCacheStatic(item);
			}
			
			
			// swf address
			debugIt(" --> swfAddress actif ");
			SWFAddress.addEventListener(SWFAddressEvent.CHANGE, onSwfAdressChange);
			
			if(_xmlConfig.swfAddress[0] is XML && _xmlConfig.swfAddress.@url != ""){
				_isSwfAdd = true;
				
				rep = _repShared;
				if (_xmlConfig.swfAddress.@path != null && _xmlConfig.swfAddress.@path == "countryPath") rep = _repLoc;
				if (_xmlConfig.swfAddress.@path != null && _xmlConfig.swfAddress.@path == "external") rep = "";
					
				var item2:LoaderItemObject = new LoaderItemObject("xmlSwfAd", rep+_xmlConfig.swfAddress.@url);			
				_loaderManager.add(item2);
				_ressourcesManager.addToCacheStatic(item2);
			}
			
			//loadersAssets
			if(_xmlConfig.loadersAssets[0] is XML && _xmlConfig.loadersAssets.@url != ""){
			
				if (_xmlConfig.loadersAssets.@path != null && _xmlConfig.loadersAssets.@path == "countryPath") rep = _repLoc;
				if (_xmlConfig.loadersAssets.@path != null && _xmlConfig.loadersAssets.@path == "external") rep = "";
				
				var item4:LoaderItemObject = new LoaderItemObject("loadersAssets", rep+_xmlConfig.loadersAssets.@url);			
				_loaderManager.add(item4);
				_ressourcesManager.addToCacheStatic(item4);
			}
			
			
			_loaderManager.addEventListener(LoaderEvent.COMPLETED, onRequiredRessourcesCompleted);
			_loaderManager.start();
		}
		//----------------------------------------------------------------------
		/**
		 * Méthode appelé quand le xml templates est chargé
		 * @param	evt
		 */
		private function onRequiredRessourcesCompleted(evt:LoaderEvent):void 
		{
			//trace("onTemplatesXmlComplete");
			
			_loaderManager.removeEventListener(LoaderEvent.COMPLETED, onRequiredRessourcesCompleted);
			_loaderManager.reset();
			

			if(_isSwfAdd)
			{
				var listAd:XML	= new XML(String(getloaderItemRessourceGlobal("xmlSwfAd").content));
					_listAd = listAd.addressPages;
			}
			
			onReady();
			
			if (_ressourcesManager.getRessource("xmlTemplates") != null  )
			{
				// on récupère le xml
				_xmlTemplates = new XML((_ressourcesManager.getRessource("xmlTemplates") as LoaderItemObject).content as String);

				defineFirstPage();
				
			}else {
				
				_xmlTemplates = _xmlConfig.contentDisplayed[0];
				
				startLoadRessources();
			}
			
			
			
		}
		//----------------------------------------------------------------------
		/**
		 * Méthode appelé quand le containerLoader est prêt à afficher le loading et charger les ressources
		 */
		public function onReady():void
		{
			
			
		}
		//----------------------------------------------------------------------
		private function defineFirstPage():void
		{
			//debugIt("defineFirstPage");
			_flashVarNavigationName = _xmlConfig.flashvarNavigationName.@name;
		

			// on récupère l'id de la première page (LoaderItemGroup) à afficher du xml templates
			_deepLinkToLoad = _xmlTemplates.pages.@firstPage;
			
			// si existe on récupère l'id de la première page à charger depuis la flashvar
			if(LoaderInfo(loaderInfo).parameters[_flashVarNavigationName] != null)
			{
				//debugIt("LoaderInfo(loaderInfo).parameters[_flashVarNavigationName] " + LoaderInfo(loaderInfo).parameters[_flashVarNavigationName]);
				_deepLinkToLoad = LoaderInfo(loaderInfo).parameters[_flashVarNavigationName];
			}
			
			var initialSwfAddress:String = SWFAddress.getValue();
			debugIt("initialSwfAddress " + initialSwfAddress);

			
			if (_deepLinkToLoad.substring(0, 1) != "/") {
				_deepLinkToLoad = "/" + _deepLinkToLoad;
			}

			
			if(initialSwfAddress != "" && initialSwfAddress != "/")
			{
				if(_isSwfAdd)
					_deepLinkToLoad = getDeepLinkFromSwfAdd(initialSwfAddress);
				else 
					_deepLinkToLoad = initialSwfAddress;
					
			}

			//debugIt("_deepLinkToLoad " + _deepLinkToLoad);
			
			
			// on regarde si l'id page est id ou un xml
			if (_deepLinkToLoad.indexOf(".xml") != -1)
			{	
				var urlClean:String = _deepLinkToLoad;
				if ( _deepLinkToLoad.substring(0, 1) == "/") {
					urlClean = _deepLinkToLoad.substr(1, _deepLinkToLoad.length);
				}
				
				
				_loaderItemXmlContent = new LoaderItemObject("xmlContent", _repLoc + urlClean);
				addEventListener("__onXmlContentLoaded", startLoadRessources);
				

				
				_loaderManager.addEventListener(LoaderEvent.COMPLETED, onXmlContentCompleted);
				_loaderManager.reset();
				_loaderManager.add(_loaderItemXmlContent);
				_loaderManager.start();
				
				
			}else
			{
				startLoadRessources();
			}
			

			
		}
		//----------------------------------------------------------------------
		private function onXmlContentCompleted(evt:LoaderEvent):void 
		{	
			_loaderManager.removeEventListener(LoaderEvent.COMPLETED, onXmlContentCompleted);

			_xmlContentPage = new XML(_loaderItemXmlContent.content as String);
			
			if (_xmlContentPage.children()[0].@uiRessource != undefined)
			{	
				dispatchEvent(new Event("__onXmlContentLoaded"));
			}else {
				
				trace("XXXX Error xml content, manque idTemplate ");
			}
			
			
		}
		
		// retire les indications de sous niveau de la chaine id page
		private function getIdPageClean(id:String):String {
			
			
			var idPage:String = id;
			var tab:Array = id.split(_splitDeepLink);
			if (tab != null && tab.length > 1) idPage = tab[1];
			
			
			return idPage;
		}

		//----------------------------------------------------------------------
		private function isInXmlContent(nameNode:String):Boolean
		{
			
			for (var j:int = 0; j < _xmlContentPage.children()[0].content.children().length(); j++)
			{
				if (nameNode == _xmlContentPage.children()[0].content.children()[j].name()) {
					return true;
				}
				
			}
			
			return false;
			
		}
		
		
		//----------------------------------------------------------------------
		private function startLoadRessources(evt:Event = null):void 
		{
			
			//tableau qui va contenir les ressources initiales à charger
			var tabRessourceInitial:Array = new Array();
			/*debugIt("");
			debugIt("------------------------------------- ");
			debugIt("startLoadRessources ");
			debugIt("------------------------------------- ");
			debugIt("idFirstPage " + _deepLinkToLoad);*/
			

			//------------------------------------------
			// recup des ressources global à charger
			//------------------------------------------
			// on récupère du xml config les ressources global à chargé qu'on range des dans object LoaderItemObject
			for (var i:int = 0; i < _xmlConfig.ressourcesGlobal.children().length(); i++)
			{
				var item:LoaderItemObject = _ressourcesManager.getRessourceGlobal( _xmlConfig.ressourcesGlobal.children()[i].@id );
				//_ressourcesManager.addToCacheStatic(item); par defaut en cache
				tabRessourceInitial.push(item);
			}
			
			
			//------------------------------------------
			// recup des clips de la structure du site à charger
			//------------------------------------------
			for (i = 0; i < _xmlTemplates.structure.clip.length(); i++)
			{
				
				var item2:LoaderItemObject = _ressourcesManager.getRessourceClipStructure(  _xmlTemplates.structure.clip[i].@id );
				//_ressourcesManager.addToCacheStatic(item2); par defaut en cache
				tabRessourceInitial.push(item2);
			}
			
			
			//------------------------------------------
			// première page à charger
			//------------------------------------------

			if (_deepLinkToLoad != null && _deepLinkToLoad != "")
			{
				_deepLinkFirst = _deepLinkToLoad;
				
				var itemPage:LoaderItemGroup;
				var itemRessource:LoaderItemGroup;
				var uipage:String;
				
					
				if (_deepLinkToLoad.indexOf(".xml") != -1)
				{	
					_instance.removeEventListener("__onXmlContentLoaded", startLoadRessources);
					
					// si le xml chargé à une déclaration dans la liste des pages de templates.xml
					uipage = _deepLinkToLoad;
					
	
					itemPage = _ressourcesManager.getRessourcePage(uipage) as LoaderItemGroup;
					if (itemPage != null) {
						tabRessourceInitial.push(itemPage);
						_ressourcesManager.addToCachePriority(itemPage);
					}
					
					itemRessource =  _ressourcesManager.getRessourceGroup( _xmlContentPage.children()[0].@uiRessource) as LoaderItemGroup;
					if (itemRessource != null) {
						tabRessourceInitial.push(itemRessource);
						_ressourcesManager.addToCachePriority(itemRessource);
					}

					
				}else
				{
					uipage = getIdPageClean(_deepLinkToLoad);

					
					itemPage = _ressourcesManager.getRessourcePage(uipage) as LoaderItemGroup;
					if (itemPage != null)
					{
						tabRessourceInitial.push(itemPage);
						_ressourcesManager.addToCachePriority(itemPage);

						var nodePage:XML = _xmlTemplates.pages.children().(@uipage == itemPage.id)[0];
						itemRessource = _ressourcesManager.getRessourceGroup(nodePage.@uiRessource) as LoaderItemGroup;
						if (itemRessource != null) {
							tabRessourceInitial.push(itemRessource);
							_ressourcesManager.addToCachePriority(itemRessource);
						}
					}else {
						_deepLinkToLoad = "";
					}
					
				}
				
				
			}	
			
			

			

			// on lance le chargement
			_loaderManager.reset();
			_loaderManager.tabToLoad = tabRessourceInitial;
			_loaderManager.addEventListener(LoaderEvent.COMPLETED, onRessourcesLoaded);
			_loaderManager.addEventListener(LoaderEvent.PROGRESS, onRessourcesProgress);
			_loaderManager.start();
			
			//affichage de la progression du chargement
			_loaderPanel = _loaderPanelSite;
			_loaderPanel.display();	
			
		}
		

		//----------------------------------------------------------------------
		private function onRessourcesProgress(evt:LoaderEvent):void 
		{
			_loaderPanel.setProgress(evt.percent);
			
		}
		//----------------------------------------------------------------------
		private function onRessourcesLoaded(evt:LoaderEvent):void 
		{
			/*debugIt("-----------------------------------------------------");
			debugIt("ON RESSOURCES LOADED");
			debugIt("-----------------------------------------------------");*/
			_loaderManager.removeEventListener(LoaderEvent.COMPLETED, onRessourcesLoaded);
			_loaderManager.removeEventListener(LoaderEvent.PROGRESS, onRessourcesProgress);

			_idCurrentPage = _deepLinkToLoad;
			
			_loaderPanel.close();
			
			
			_instance.dispatchEvent(new ContainerLoaderEvent(ContainerLoaderEvent.RESSOURCES_LOADED));
				
			
		}
		
		
		
		
		//----------------------------------------------------------------------
		//----------------------------------------------------------------------
		//----- Gestion chargement couple Page/ressource
		//----------------------------------------------------------------------
		//----------------------------------------------------------------------

		public function loadPage(id:String):void 
		{
			
			
			//if (_deepLinkFirst == null || ( _deepLinkFirst != null && _deepLinkFirst != id))
			//{
				/*debugIt("  ");
				debugIt("  ");
				debugIt(">>>>>  ");
				debugIt("loadPage " + id);
				debugIt("_deepLinkFirst " + _deepLinkFirst);
				debugIt(">>>>>  ");*/
				
				_deepLinkToLoad = id;
				
				if (id.indexOf(".xml") != -1 )
				{

					_instance.loadPageXml();
					
				}else
				{
					_instance._loadPage();
				}
			/*}else {
				
				debugIt("_deepLinkFirst " + _deepLinkFirst);
				
				_deepLinkFirst = null;
				
				// event
				var ev:ContainerLoaderEvent = new ContainerLoaderEvent(ContainerLoaderEvent.RESSOURCES_PAGE_LOADED);
				_instance.dispatchEvent(ev);
				
				
			}*/
			
		}
		private function _loadPage(evt:Event = null):void 
		{

			//trace("_onLoadingPage " + _onLoadingPage);
			if (!_onLoadingPage)
			{
	
					var uipage:String = getIdPageClean(_deepLinkToLoad);
					//trace("uipage " + uipage);
					
					
					var itemPage:LoaderItemGroup = _ressourcesManager.getRessourcePage(uipage) as LoaderItemGroup;
					var pageData:PageData = _dataManager.getPageData(uipage);
					var itemRessource:LoaderItemGroup;
					

					if (_xmlTemplates.pages.children().(@uipage == uipage)[0] is XML && itemPage != null)
					{
						
						
						_loaderPanel = _loaderPanelPage;

						if (pageData.uiRessource != null)
						{
							itemRessource = _ressourcesManager.getRessourceGroup(pageData.uiRessource) as LoaderItemGroup;
						}
										

						if (itemRessource != null && !itemRessource.completed)
						{
							_onLoadingPage = true;
							_loaderPanel.display();
							_ressourcesManager.addEventListener(LoaderEvent.PRIORITY_COMPLETED, onPriorityLoadCompleted);
							_ressourcesManager.addEventListener(LoaderEvent.PRIORITY_PROGRESS, onPriorityLoadProgress);
							_ressourcesManager.loadInPriority(itemRessource, itemPage);
						}else if (!itemPage.completed)
						{
							_onLoadingPage = true;
							_loaderPanel.display();
							_ressourcesManager.addEventListener(LoaderEvent.PRIORITY_COMPLETED, onPriorityLoadCompleted);
							_ressourcesManager.addEventListener(LoaderEvent.PRIORITY_PROGRESS, onPriorityLoadProgress);
							_ressourcesManager.loadInPriority(itemPage);

						}else {
							_idCurrentPage = _deepLinkToLoad;
							
							// event
							var ev:ContainerLoaderEvent = new ContainerLoaderEvent(ContainerLoaderEvent.RESSOURCES_PAGE_LOADED);
							ev.deepLink = _deepLinkToLoad;
							_instance.dispatchEvent(ev);
							
							_onLoadingPage = false;
							
						}
					}else {		
						debugIt("XXXXX  pas de page à charger pour le deepLink " + _deepLinkToLoad);
						_onLoadingPage = false;
						
						// event
						var ev4:ContainerLoaderEvent = new ContainerLoaderEvent(ContainerLoaderEvent.ERROR_LOAD);
						_instance.dispatchEvent(ev4);

					}
					
				
			}else{
			
					debugIt("XXXX LOAD not. Un Loading est déja en cours !");
					// event
					var ev3:ContainerLoaderEvent = new ContainerLoaderEvent(ContainerLoaderEvent.ERROR_LOAD);
					_instance.dispatchEvent(ev3);
					
					_onLoadingPage = false;
					
			}
			
		}


		private function onPriorityLoadCompleted(evt:LoaderEvent):void 
		{
			
			_ressourcesManager.removeEventListener(LoaderEvent.PRIORITY_COMPLETED, onPriorityLoadCompleted);
			_ressourcesManager.removeEventListener(LoaderEvent.PRIORITY_PROGRESS, onPriorityLoadProgress);
			
			//debugIt("--> onPriorityLoadCompleted");
			_loaderPanel.close();
			
			_idCurrentPage = _deepLinkToLoad;
			
			// event
			var ev:ContainerLoaderEvent = new ContainerLoaderEvent(ContainerLoaderEvent.RESSOURCES_PAGE_LOADED);
			ev.deepLink = _deepLinkToLoad;
			_instance.dispatchEvent(ev);
			
			_onLoadingPage = false;
			


			
		}
		private function onPriorityLoadProgress(evt:LoaderEvent):void 
		{
			_loaderPanel.setProgress( evt.percent);
		}	
		
		
		//----------------------------------------------------------------------
		//----------------------------------------------------------------------
		//----- loadRessource indépendante du systeme d'affichage de page
		//----------------------------------------------------------------------
		//----------------------------------------------------------------------
		public function loadGroupRessource(obj:Object):LoaderItemGroup
		{
			return _instance._loadGroupRessource(obj);

		}
		
		public function _loadGroupRessource(obj:Object):LoaderItemGroup
		{
			//_onLoadingPage = true;
			var item:LoaderItemGroup;
			
			if (obj is String) {
				
				item = getLoaderItemPage(obj as String);
				if (item == null) item = getLoaderItemRessource(obj as String);
			}else if (obj is LoaderItemGroup) {
				item = obj as LoaderItemGroup;
			}
			
			
			
			if (item != null && !item.completed) {
				
				//_loaderPanel = _loaderPanelPage;
				//_loaderPanel.container = this;
				
				_ressourcesManager.addEventListener(LoaderEvent.PRIORITY_COMPLETED, onRessourceCompleted);
				//_ressourcesManager.addEventListener(LoaderEvent.PRIORITY_PROGRESS, onPriorityLoadProgress);
				//_loaderPanel.display();
				
				_ressourcesManager.loadInPriority(item);
				
				function onRessourceCompleted(evt:LoaderEvent):void 
				{
					//_loaderPanel.close();
					_ressourcesManager.removeEventListener(LoaderEvent.PRIORITY_COMPLETED, onRessourceCompleted);
					//_ressourcesManager.removeEventListener(LoaderEvent.PRIORITY_PROGRESS, onPriorityLoadProgress);
				}
				
				return item;
				
			}else {
				//_onLoadingPage = false;
				return null;
			}
			
			
			
			
		}
		
		//----------------------------------------------------------------------
		//----------------------------------------------------------------------
		//----- Gestion loading in backgound et mise en cache
		//----------------------------------------------------------------------
		//----------------------------------------------------------------------
		//----------------------------------------------------------------------
		public function addInBackgroundLoading(id:String):void
		{
			var item:LoaderItemGroup = getLoaderItemPage(id);
			if (item == null) item = getLoaderItemRessource(id);
			
			
			if(item  != null) _ressourcesManager.addToLoadInBackground(item);
			
		}
		public function addToCacheStatic(id:String):void
		{
			var item:LoaderItemGroup = getLoaderItemPage(id);
			if (item == null) item = getLoaderItemRessource(id);
			
			if(item  != null) _ressourcesManager.addToCacheStatic(item);
			
		}
		
		public function startBackgoundLoading():void
		{
			debugIt("");
			debugIt("");
			debugIt("-------------------------");
			debugIt("startLoadInBackground");
			debugIt("-------------------------");
			
			_ressourcesManager.loadStaticRessources();
		}
		//----------------------------------------------------------------------
		private function onBackgroundCompleted(evt:LoaderEvent):void 
		{
			/*debugIt("--> onBackgroundCompleted");
			debugIt("---------------------------------------------------------------------------");*/
			_loaderManager.removeEventListener(LoaderEvent.COMPLETED, onBackgroundCompleted);
			
			// event
			var ev:ContainerLoaderEvent = new ContainerLoaderEvent(ContainerLoaderEvent.FULL_LOADED);
			_instance.dispatchEvent(ev);	
		}
		
		
		//----------------------------------------------------------------------
		// load de page defini dans un xml externe
		//----------------------------------------------------------------------
		private function loadPageXml():void 
		{
			_xmlContentPage = null;
			
			var urlClean:String = _deepLinkToLoad;
			if ( _deepLinkToLoad.substring(0, 1) == "/") {
				urlClean = _deepLinkToLoad.substr(1, _deepLinkToLoad.length);
			}
			
			
			/*var tab:Array = _deepLinkToLoad.split(_splitDeepLink);
			if (tab != null && tab.length > 1) idClean = tab[0];*/
			
			
			_loaderPanel = _loaderPanelPage;
			_loaderPanel.display();
			
			_loaderItemXmlContent = new LoaderItemObject("xmlContent", _repLoc + urlClean);
			_instance.addEventListener("__onXmlContentLoaded", _loadPageXml);
			
			
			_loaderManager.addEventListener(LoaderEvent.COMPLETED, onXmlContentCompleted);
			_loaderManager.loadInPriority(_loaderItemXmlContent);

		}
		private function _loadPageXml(evt:Event = null):void 
		{
			//debugIt(" --> _loadPageXml");
			
			
			//trace("_onLoadingPage " + _onLoadingPage);
			if (!_onLoadingPage)
			{
	
					
						var itemRessource:LoaderItemGroup;
					
						
						
						_loaderPanel = _loaderPanelPage;

						
						if (_xmlContentPage.children()[0].@uiRessource != null)
						{
							itemRessource = _ressourcesManager.getRessourceGroup( _xmlContentPage.children()[0].@uiRessource) as LoaderItemGroup;
						}
										

						//trace("itemRessource " + itemRessource);
						//trace("itemRessource.completed " + itemRessource.completed);
						
						if (itemRessource != null && !itemRessource.completed)
						{
							_onLoadingPage = true;
							_loaderPanel.display();
							_ressourcesManager.addEventListener(LoaderEvent.PRIORITY_COMPLETED, onPriorityLoadCompleted);
							_ressourcesManager.addEventListener(LoaderEvent.PRIORITY_PROGRESS, onPriorityLoadProgress);
							_ressourcesManager.loadInPriority(itemRessource);
						}else {
							_idCurrentPage = _deepLinkToLoad;
							
							// event
							var ev:ContainerLoaderEvent = new ContainerLoaderEvent(ContainerLoaderEvent.RESSOURCES_PAGE_LOADED);
							ev.deepLink = _deepLinkToLoad;
							_instance.dispatchEvent(ev);
							
							_onLoadingPage = false;
							
						}
					
				
			}else{
			
					debugIt("XXXX LOAD not. Un Loading est déja en cours !");
					// event
					var ev3:ContainerLoaderEvent = new ContainerLoaderEvent(ContainerLoaderEvent.ERROR_LOAD);
					_instance.dispatchEvent(ev3);
					
					_onLoadingPage = false;
					
			}
			
			
		}
		
		
		
		//----------------------------------------------------------------------
		// Debug
		//----------------------------------------------------------------------
		private function initDebug():void 
		{
			if ( String(_xmlConfig.debug.@value) == "true") {
				_debugMode = true;
			}
			
			
			
			if(_debugMode)
			{
				Debug.clear() 
				Debug.monitor(stage);
				
				
			}
			
		} 
		
		public function debugIt(str:Object, tmpNum:Number = 1):void 
		{
			
			
			if (Capabilities.playerType == "External")
			{
				trace(str);
			}else if(_debugMode)
			{
				Debug.trace(str, tmpNum);
				trace(str);
			}
			
			
		}	
		
		//----------------------------------------------------------------------
		// SWF ADDRESS
		//----------------------------------------------------------------------
		public function setSwfAdrress(chaine:String, title:String = ""):void 
		{
			
			//debugIt(" setSwfAdrress " + chaine);
			
			SWFAddress.removeEventListener(SWFAddressEvent.CHANGE, _instance.onSwfAdressChange);
			
			
			if (_isSwfAdd) {
				try{
					var nodeSWFAd:XMLList = _listAd.address.(@deepLink == chaine);
					
					var valPageAd:String 	= ""	;
					var valPageTitle:String = ""	;

					
					if ( nodeSWFAd.length() > 0) {
						valPageAd 		= 	nodeSWFAd.attribute('addressPage');
						valPageTitle 	=	nodeSWFAd.attribute('titlePage');
					}else {

							var c:String = "/" + _instance.getIdPageClean(chaine);
							nodeSWFAd = _listAd.address.(@deepLink == c);

							if ( nodeSWFAd.length() > 0) {
								valPageAd 		= 	nodeSWFAd.attribute('addressPage');
								valPageTitle 	=	nodeSWFAd.attribute('titlePage');

								var tab:Array = chaine.split(c);
								if (tab.length > 1) valPageAd += tab[1];
							
							}else {
								valPageAd = chaine;
								valPageTitle = title;
							}
					}
					
					SWFAddress.setValue(valPageAd);
					if(valPageTitle != "") SWFAddress.setTitle(valPageTitle);
					
					//debugIt("SwfAdress SET CHANGE " + valPageAd);

				

				}catch (e:Error) {
					//debugIt("SwfAdress NOT Exist " + chaine );
					SWFAddress.setValue(chaine);
					if(title != "") SWFAddress.setTitle(title);
				}
			}else {
				//debugIt("SwfAdress NOT actif " + chaine );
				
				SWFAddress.setValue(chaine);
				if(title != "") SWFAddress.setTitle(title);
			}
			
			SWFAddress.addEventListener(SWFAddressEvent.CHANGE, _instance.onSwfAdressChange);
			
			
			
		}
		public function getSwfAdress():String
		{
			return SWFAddress.getValue();
		}
		public function setSwfAdrressTitle(title:String):void
		{
			SWFAddress.setTitle(title);
		}
		
		public function setPreviousSwfAdress():void {
			SWFAddress.back();
		}

		private function onSwfAdressChange(e:SWFAddressEvent):void
		{
			
			var chaine:String = e.value;
			//debugIt("chaine " + chaine);
			//debugIt("_listAd " + _listAd);
			
			if(_isSwfAdd){
				if (_listAd != null) {

						var chaineF:String 		= getDeepLinkFromSwfAdd(chaine);
						//debugIt("chaineF " + chaineF);
						
						if (chaineF != null) {
							// déclenchement event
							var evt:ContainerLoaderEvent = new ContainerLoaderEvent(ContainerLoaderEvent.SWFADRESS_CHANGE);
							evt.deepLink = chaineF;
							_instance.dispatchEvent(evt);
						}

					
				}
			}else {
				// déclenchement event en passant la chaine tel quelle
				var evt2:ContainerLoaderEvent = new ContainerLoaderEvent(ContainerLoaderEvent.SWFADRESS_CHANGE);
				evt2.deepLink = chaine;
				_instance.dispatchEvent(evt2);
			}
				
		}
		public function getDeepLinkFromSwfAdd(chaine:String):String
		{
			var ret:String;
			
			
			try {
				
				var chaineTest:String = chaine;
				var chaineRest:String = "";
				
				while ( chaineTest != "")
				{
					
					var nodeSWFAd:XMLList = _listAd.address.(@addressPage == chaineTest);
					debugIt("nodeSWFAd " + nodeSWFAd);
					if ( nodeSWFAd.length() > 0) {
						if( chaineRest != "") ret = nodeSWFAd.attribute('deepLink') + "/" + chaineRest;
						else ret = nodeSWFAd.attribute('deepLink');
						chaineTest = null;
						break;
					}else {
						var tabChaine:Array = chaineTest.split("/");
						chaineTest = "";
						for (var i:int = 1; i < tabChaine.length-1; i++) 
						{
							chaineTest += "/" + tabChaine[i];
						}
						if( chaineRest != "") chaineRest = tabChaine[tabChaine.length - 1] + "/" + chaineRest;
						else chaineRest = tabChaine[tabChaine.length - 1];
					}
					
				}
				
				if ( ret == null) {
					ret = chaine;
				}
				

			}catch (e:Error) {
				ret = chaine;
			}
			debugIt("getDeepLinkFromSwfAdd " + ret);
			
			return ret;
			
		}
	}
}